package siafi.util;


import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.StringTokenizer;

/**
 *
 * @author cesardoncel
 */
public class ValidarPwd {
    
    public Boolean validar(String usr, String pwd) throws FileNotFoundException, IOException, NoSuchAlgorithmException{ 
        
        File fileP = new File("usrCompl.txt");
        //System.err.println(fileP.getAbsolutePath());
        FileReader fr = new FileReader(fileP);
        BufferedReader br = new BufferedReader(fr);
        String lineas = "";   
        String pwdHex = hex(pwd);
        int x = 0;
        while ((lineas = br.readLine()) != null && x == 0){
            String usrAux = "";
            String pwdAux = "";
            StringTokenizer st = new StringTokenizer(lineas, "\t");
            int i = 0;
            while (st.hasMoreTokens()){
                if (i == 0){
                    usrAux = st.nextToken();                    
                } else 
                    pwdAux = st.nextToken();
                i++;                
            }
            if (usrAux.equals(usr)){
                if (pwdAux.equals(pwdHex)){
                    x = 1;
                    return true;
                }
            } 
        }
        return false;
    }
    
    public String hex (String pwd) throws NoSuchAlgorithmException{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(pwd.getBytes());

        byte byteData[] = md.digest();

        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int ni = 0; ni < byteData.length; ni++) {
            sb.append(Integer.toString((byteData[ni] & 0xff) + 0x100, 16).substring(1));
        }
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
        for (int m=0;m<byteData.length;m++) {
                String hex=Integer.toHexString(0xff & byteData[m]);
                if(hex.length()==1) hexString.append('0');
                hexString.append(hex);
        }
        String hex = hexString.toString();
        return hex;
    }
    
}
